package com.zxy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zxy.common.result.Result;
import com.zxy.pojo.dto.DictTypeQueryVO;
import com.zxy.pojo.entity.DictType;
import com.zxy.pojo.entity.SysDept;
import com.zxy.pojo.entity.SysNotice;
import com.zxy.pojo.vo.DictTypePageResponseVO;
import com.zxy.pojo.vo.NoticePageResponseVO;
import com.zxy.pojo.vo.BusinessChangeStatsVo;
import com.zxy.service.SystemService;
import com.zxy.service.ReportService;
import com.zxy.util.OperLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;
import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping
public class SystemController {
    @Autowired
    public SystemService systemService;
    
    @Autowired
    private ReportService reportService;

    /**
     * 字典类型列表分页查询接口
     * 路径：GET /system/dict/type/list
     * 参数：query参数（pageNum、pageSize、dictName、dictType、status、params[beginTime]、params[endTime]）
     */
    @GetMapping("/system/dict/type/list")
    @OperLog(title = "字典类型列表分页查询接口",businessType = 0,saveParams = true,saveResult = true)
    public DictTypePageResponseVO getDictTypeList(
            // @Validated：触发VO中的参数校验；GET请求自动绑定query参数
            @Validated DictTypeQueryVO queryVO
    ) {
        // 调用Service分页查询，直接返回响应VO
        return systemService.getDictTypePage(queryVO);
    }
    @GetMapping("/system/dict/type/{id}")
    public Result<DictType> selectDictType(@PathVariable Long id){
        /*LambdaQueryWrapper<DictType> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DictType::getDictId,id);
        return Result.success(systemService.getOne(wrapper));*/
        return Result.success(systemService.getOne(new LambdaQueryWrapper<DictType>().eq(DictType::getDictId, id)));
    }
    @PostMapping("/system/dict/type")
    public Result saveDictType(@RequestBody DictType dictType){
        try {
            systemService.save(dictType);
            return Result.success();
        } catch (Exception e) {
            if (e.getCause() instanceof SQLIntegrityConstraintViolationException) {
                return Result.error("字典名称已存在");
            }
            throw e;
        }
    }
    @DeleteMapping("/system/dict/type/{id}")
    public Result deleteDictType(@PathVariable Long id){
        systemService.removeById(id);
        return Result.success();
    }
    @PutMapping("/system/dict/type")
    public Result updateDictType(@RequestBody DictType dictType){
        try {
            systemService.updateById(dictType);
            return Result.success();
        } catch (Exception e) {
            if (e.getCause() instanceof SQLIntegrityConstraintViolationException) {
                return Result.error("字典名称已存在");
            }
            throw e;
        }
    }



    /**
     * 已读/未读通知分页列表
     * 接口路径：GET /system/notice/pagelist/{readStatus}
     * @param readStatus 0=未读，1=已读
     */
    @GetMapping("/system/notice/pagelist/{readStatus}")
    public NoticePageResponseVO getNoticePageList(@PathVariable Integer readStatus) {
        // 1. 调用Service查询通知列表
        List<SysNotice> noticeList = systemService.getNoticeListByReadStatus(readStatus);

        // 2. 封装响应VO
        NoticePageResponseVO responseVO = new NoticePageResponseVO();
        responseVO.setTotal((long) noticeList.size()); // 总记录数
        responseVO.setRows(noticeList);               // 当前页数据
        return responseVO;
    }


    /**
     * 部门树形选择接口（无参数GET请求）
     * 路径：GET /system/dept/treeselect
     */
    @GetMapping("/system/dept/treeselect")
    public Result<List<SysDept>> getDeptTreeSelect() {
        // 1. 调用Service获取树形部门数据
        List<SysDept> deptTree = systemService.getDeptTreeSelect();

        // 2. 封装成通用响应VO（匹配msg/code/data格式）
        return Result.success(deptTree);
    }
    
    /**
     * 业务变更统计接口
     * 路径：GET /index/businessChangeStatistics
     * @param beginCreateTime 开始日期
     * @param endCreateTime 结束日期
     * @return 业务变更统计数据
     */
    @GetMapping("/index/businessChangeStatistics")
    public Result<List<BusinessChangeStatsVo>> businessChangeStatistics(
            @RequestParam("beginCreateTime") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate beginCreateTime,
            @RequestParam("endCreateTime") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endCreateTime) {
        // 调用Service查询业务变更统计数据
        List<BusinessChangeStatsVo> statsList = reportService.businessChangeStatistics(beginCreateTime, endCreateTime);
        
        // 封装成通用响应格式
        return Result.success(statsList);
    }
}